<template>
  <div>
    <a-card title="心理测评历史">
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :loading="loading"
        :custom-row="customRow"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'created'">
            {{ formatDate(record.created) }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" danger size="small" @click.stop="handleDelete(record)">删除</a-button>
          </template>
          <template v-else>
            {{ record[column.dataIndex] }}
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="detailModalVisible"
      title="测评报告详情"
      width="1500px"
      :footer="null"
    >
      <div v-if="detail.riskLevel">
        <a-alert
          :message="`风险等级: ${detail.riskLevel}`"
          :type="detail.riskLevel === 'high' ? 'error' : detail.riskLevel === 'medium' ? 'warning' : 'success'"
          show-icon
          style="margin-bottom: 16px"
        />
        <a-card title="分析结果" style="margin-bottom: 16px">
          <div v-html="analysisHtml" />
        </a-card>
        <a-card title="建议">
          <div v-html="suggestionHtml" />
        </a-card>
      </div>
      <div v-else>
        暂无报告详情
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useMarkdownRender } from './useMarkdownRender'

const columns = [
  { title: '用户描述', dataIndex: 'psychologicalDescription', key: 'psychologicalDescription' },
  { title: '创建时间', dataIndex: 'created', key: 'created' },
  { title: '操作', dataIndex: 'action', key: 'action' }
]

const data = ref([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
  showTotal: total => `共 ${total} 条`
})

function formatDate(dateStr) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return d.toLocaleString()
}

const fetchData = async (page = 1, pageSize = 20) => {
  loading.value = true
  try {
    const res = await axios.get('http://192.168.0.22:7044/api/module/AIMentalHealth/Page', {
      params: {
        PageNumber: page,
        PageSize: pageSize
      }
    })
    if (res.data && res.data.success) {
      data.value = res.data.data
      pagination.value.total = res.data.total
      pagination.value.current = res.data.current
      pagination.value.pageSize = res.data.pageSize
    }
  } finally {
    loading.value = false
  }
}

function handleTableChange(pag) {
  fetchData(pag.current, pag.pageSize)
}

const { html: analysisHtml, renderMarkdown: renderAnalysis } = useMarkdownRender()
const { html: suggestionHtml, renderMarkdown: renderSuggestion } = useMarkdownRender()

const detailModalVisible = ref(false)
const detail = ref({ riskLevel: '', analysis: '', suggestion: '' })

// 添加行点击处理函数
const customRow = (record) => {
  return {
    onClick: () => {
      showDetail(record)
    },
    style: { cursor: 'pointer' }
  }
}

function showDetail(record) {
  if (!record.analysisResult) return
  try {
    const result = JSON.parse(record.analysisResult)
    detail.value = result
    renderAnalysis(result.analysis)
    renderSuggestion(result.suggestion)
    detailModalVisible.value = true
  } catch (e) {
    detail.value = { riskLevel: '', analysis: '报告解析失败', suggestion: '' }
    renderAnalysis('报告解析失败')
    renderSuggestion('')
    detailModalVisible.value = true
  }
}

// 删除记录方法
async function handleDelete(record) {
  if (!record.id) return
  try {
    loading.value = true
    const res = await axios.delete(`http://192.168.0.22:7044/api/module/AIMentalHealth/${record.id}`)
    if (res.data && res.data.success) {
      fetchData(pagination.value.current, pagination.value.pageSize)
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>